<?php

require_once "access_token.php";
require_once "helper.php";

class helper_api {

	private $agent_id;
	private $access_token;

	public function __construct() {
		$this -> agent_id = 'helper';
		$this -> access_token = new access_token("helper");
	}

	/**
	 * 在请求的企业微信接口后面自动附加token信息
	 */
	private function append_token($url) {
		$token = $this -> access_token -> get_access_token();

		if (strrpos($url, "?", 0) > -1) {
			return $url . "&access_token=" . $token;
		} else {
			return $url . "?access_token=" . $token;
		}
	}

	/**
	 * 上传图片
	 * 注意：上传大文件时可能需要先调用 set_time_limit(0) 避免超时
	 * 注意：数组的键值任意，但文件名前必须加@，使用单引号以避免本地路径斜杠被转义
	 * @param array $data {"media":'@Path\filename.jpg'}
	 *
	 * @return boolean|array
	 */
	public function upload_media($data, $type) {
		$url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=$type";

		$ret = http_post($this -> append_token($url), $data);
		$ret = $ret["content"];

		if ($ret) {
			$json = json_decode($ret, true);
			if (!$json || !empty($json['errcode'])) {
				$this -> errCode = $json['errcode'];
				$this -> errMsg = $json['errmsg'];
				return false;
			}
			return $json;
		}
		return false;
	}

	public function get_user_id($code) {
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?code=" . $code;

		$ret = http_get($this -> append_token($url));
		$ret = $ret["content"];
		$return = json_decode($ret, true);
		return $return['UserId'];
	}

}
